<script setup lang="ts">

import {Message, Modal, TableColumnData} from "@arco-design/web-vue";
import {
  addUser as addUserApi,
  list,
  removeUser,
  resetPassword as resetPasswordApi,
  update,
  User
} from "@/api/sysController.ts";
import {computed, h, onMounted, ref, watch} from "vue";
import {userStore} from "@/store/user.ts";
import {useWindowSize} from "@vueuse/core/index";

const visible = ref<boolean>(false)
const editVisible = ref<boolean>(false)
const {width} = useWindowSize()
const isPhone = computed(() => {
  return width.value < 768
})

const columns: TableColumnData[] = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '用户名',
    dataIndex: 'username',
  },
  {
    title: '角色',
    dataIndex: 'role',
  },
  {
    title: '开票权限',
    slotName: 'sellerRole'
  },
  {
    title: '账号状态',
    slotName: 'userStatus'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    render: ({record}) => {
      if(record.email) {
        return h('span',record.email)
      } else {
        return h('span', '--')
      }
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '上次登录时间',
    dataIndex: 'lastLoginTime',
  },
  {
    title: '操作',
    slotName: 'action'
  }
]

const roleOptions = [
  {
    label: '管理员',
    value: '管理员'
  },
  {
    label: '公司文员',
    value: '公司文员'
  },
  {
    label: '开票员',
    value: '开票员'
  }
]
const sellerOptions = [
  {
    label: '顺丰',
    value: '顺丰'
  },
  {
    label: '合丰',
    value: '合丰'
  }
]
const addUserFormRef = ref()
const editUserFormRef = ref()
const data = ref({
  tableData: [] as User[]
})

const addUserForm = ref({
  username: '',
  role: '',
  sellerRoleList: []
})

const rules = {
  username: [
    {required: true, message: '请输入用户名'}
  ],
  role: [
    {required: true, message: '请选择角色'}
  ],
  sellerRoleList: [
    {required: true, message: '请选择开票主体'}
  ]
}

const statusColor = (value: '正常' | '待激活' | '冻结' | '初始化') => {
  const map = {
    '正常': 'blue',
    '待激活': 'orange',
    '冻结': 'orangered',
    '初始化': 'cyan'
  }

  if(map[value]) {
    return map[value]
  }

  return ''

}

const addUser = () => {
  visible.value = true
}

const editUser = (user: User) => {
  console.log(user, 'user')
  editVisible.value = true
  addUserForm.value.username = user.username
  addUserForm.value.role = user.role
  addUserForm.value.sellerRoleList = user.sellerRoleList
  editId.value = user.id
}

const resetAddForm = () => {
  console.log('resetAddForm')
  addUserFormRef.value.resetFields()
}

watch(visible, (val) => {
  if (!val) {
    resetAddForm()
  }
})
watch(editVisible, (val) => {
  if (!val) {
    resetAddForm()
  }
})

const handleAdd = async () => {
  return new Promise((resolve, reject) => {
    addUserFormRef.value.validate((error) => {
      if (!error) {
        addUserApi(addUserForm.value).then(() => {
          resolve(true)
          visible.value = false
          Modal.success( {
            title: '添加成功！',
            content: '添加成功，请联系用户上线并更改密码'
          })
          addUserFormRef.value.resetFields()
          getList()
        }).catch(() => {
          reject(false)
        })
      } else {
        reject(error)
      }
    })
  })

}

const editId = ref<string>('')
const handleEdit = async () => {
  return new Promise((resolve, reject) => {
    editUserFormRef.value.validate((error) => {
      if (!error) {
        const obj = {}
        Object.assign(obj, addUserForm.value, {id: editId.value})
        update(obj).then(() => {
          resolve(true)
          editVisible.value = false
          editUserFormRef.value.resetFields()
          getList()
        }).catch(() => {
          reject(false)
        })
      } else {
        reject(error)
      }
    })
  })
}

const resetPassword = (user: User) => {
  Modal.confirm({
    title: '提示',
    content: '确定重置密码吗？重置后，密码将重置为123456',
    onOk: () => {
      if (user.id) {
        resetPasswordApi(user.id).then(() => {
          Modal.success({
            title: '重置成功',
            content: '密码将重置为123456，请联系用户登录重新设置密码'
          })
          getList()
        })
      }
    }
  })

}

const remove = (user: User) => {
  Modal.confirm({
    title: '提示',
    content: '确定删除吗？',
    onOk: () => {
      if (user.id) {
        removeUser(user.id).then(() => {
          getList()
        })
      }
    }
  })
}

const getList = async () => {
  data.value.tableData = await list()
}

const resetPwdBtnShow = (user: User) => {
  if (user.role === '管理员') {
    return false
  }
  if (user.id === userStore().userInfo?.id) {
    return false
  }
  return true
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div>
    <a-page-header title="用户管理" :show-back="false">
      <template #extra>
        <a-button type="primary" @click="addUser">添加用户</a-button>
      </template>
    </a-page-header>
    <div class="main">
      <a-table size="small" :columns="columns" :data="data.tableData" v-if="!isPhone">
        <template #sellerRole="{ record }">
          <template v-if="record.sellerRoleList">
            <a-tag v-for="item in record.sellerRoleList" style="margin-right: 5px;">{{ item }}</a-tag>
          </template>
          <template v-else>--</template>
        </template>
        <template #userStatus="{ record }">
          <a-tag :color="statusColor(record.status)">{{ record.status }}</a-tag>
        </template>
        <template #action="{ record }">
          <a-button size="mini" v-if="resetPwdBtnShow(record)" @click="editUser(record)">编辑</a-button>
          <a-button size="mini" v-if="resetPwdBtnShow(record)" status="danger" @click="remove(record)">删除</a-button>
          <a-button size="mini" v-if="resetPwdBtnShow(record)" @click="resetPassword(record)">重置密码</a-button>
        </template>
      </a-table>
      <div class="phone-card" v-else>
        <div class="card-item" v-for="item in data.tableData">
          <div class="username">{{ item.username }}
            <a-tag>{{ item.role }}</a-tag>
          </div>
          <div class="handle-button">
            <a-button size="mini" v-if="resetPwdBtnShow(item)" @click="editUser(item)">编辑</a-button>
            <a-button size="mini" v-if="resetPwdBtnShow(item)" status="danger" @click="remove(item)">删除</a-button>
            <a-button size="mini" v-if="resetPwdBtnShow(item)" @click="resetPassword(item)">重置密码</a-button>
          </div>
        </div>
      </div>
    </div>

    <a-modal v-model:visible="visible" title="添加用户" :on-before-ok="handleAdd" :width="isPhone ? '90vw' : undefined">
      <a-form :model="addUserForm" :rules="rules" ref="addUserFormRef" :layout="isPhone ? 'vertical' : 'horizontal'">
        <a-form-item label="用户名" field="username">
          <a-input v-model="addUserForm.username"></a-input>
        </a-form-item>
        <a-form-item label="角色" field="role">
          <a-select v-model="addUserForm.role" :options="roleOptions"></a-select>
        </a-form-item>
        <a-form-item label="开票主体(可多选)" field="sellerRoleList" v-if="addUserForm.role === '开票员'">
          <a-select v-model="addUserForm.sellerRoleList" multiple :options="sellerOptions"></a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="editVisible" title="修改用户" :on-before-ok="handleEdit"
             :width="isPhone ? '90vw' : undefined">
      <a-form :model="addUserForm" :rules="rules" ref="editUserFormRef" :layout="isPhone ? 'vertical' : 'horizontal'">
        <a-form-item label="用户名" field="username">
          <a-input v-model="addUserForm.username" disabled></a-input>
        </a-form-item>
        <a-form-item label="角色" field="role">
          <a-select v-model="addUserForm.role" :options="roleOptions"></a-select>
        </a-form-item>
        <a-form-item label="开票主体(可多选)" field="sellerRoleList" v-if="addUserForm.role === '开票员'">
          <a-select v-model="addUserForm.sellerRoleList" multiple :options="sellerOptions"></a-select>
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<style scoped lang="scss">
.main {
  padding: 20px;

  .phone-card {
    .card-item {
      display: flex;
      justify-content: space-between;
      width: 93%;
      border: 1px solid var(--color-border);
      padding: 10px;
      border-radius: 4px;
      margin-bottom: 10px;
      box-shadow: 0 2px 4px 0 rgb(0 0 0 / 10%);
    }
  }
}
</style>
